In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
Make sure that you've downloaded the required human and dog datasets:
Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.
Download the human dataset. Unzip the folder and place it in the home diretcory, at location /lfw.
Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.
In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.
# Install cv2 library
!pip install -q opencv-python
# Download OpenCV's implementations of Haar feature-based cascade classifiers to detect human faces in images
haarcascades_baseurl = 'https://raw.githubusercontent.com/opencv/opencv/master/data/'
haarcascades_types = ['haarcascades/haarcascade_frontalface_alt.xml',
'haarcascades/haarcascade_frontalface_alt2.xml',
'haarcascades/haarcascade_frontalface_alt_tree.xml',
'haarcascades/haarcascade_frontalface_default.xml']
for haarcascades_type in haarcascades_types:
!wget -q '{haarcascades_baseurl}{haarcascades_type}' -P haarcascades
# Download the dog images
!wget -q https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/dogImages.zip
!unzip -q dogImages.zip
# Download the human images
!wget -q https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/lfw.zip
!unzip -q lfw.zip lfw/*/*
# Import all dependencies for this notebook
%matplotlib inline
import numpy as np
from glob import glob
import cv2
from tqdm import tqdm
import matplotlib.pyplot as plt
from PIL import Image, ImageFile
import torch
from torch import nn, optim
from torchvision import models, transforms, datasets
import sys
import os
from google.colab import drive
gdrive_dir = '/gdrive'
drive.mount(gdrive_dir)
gdrive_dir = gdrive_dir+'/My Drive/Colab Notebooks/'
# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))
# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.
OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier(haarcascades_types[0])
# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector function.
human_files have a detected human face? dog_files have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.
Answer:
Human faces detected in human images: 100.0%
Human faces detected in dog images: 12.0%
human_files_short = human_files[:100]
dog_files_short = dog_files[:100]
#-#-# Do NOT modify the code above this line. #-#-#
## DONE: Test the performance of the face_detector algorithm
## on the images in human_files_short and dog_files_short.
detections_in_human_files = np.mean([face_detector(img) for img in human_files_short]) * 100
print(f'Human faces detected in human images\t{detections_in_human_files:.2f}%')
detections_in_dog_files = np.mean([face_detector(img) for img in dog_files_short]) * 100
print(f'Human faces detected in dog images\t{detections_in_dog_files:.2f}%')
We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### DONE: Test performance of another face detection algorithm.
### Feel free to use as many code cells as needed.
for haarcascades_type in haarcascades_types:
print('----- Testing', haarcascades_type)
face_cascade = cv2.CascadeClassifier(haarcascades_type)
detections_in_human_files = np.mean([face_detector(img) for img in human_files_short]) * 100
print(f'Human faces detected in human images\t{detections_in_human_files:.2f}%')
detections_in_dog_files = np.mean([face_detector(img) for img in dog_files_short]) * 100
print(f'Human faces detected in dog images\t{detections_in_dog_files:.2f}%')
print()
# Load the "haarcascade_frontalface_alt.xml"
# since it performs better than the other tested classifiers.
face_cascade = cv2.CascadeClassifier(haarcascades_types[0])
In this section, we use a pre-trained model to detect dogs in images.
The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.
# define VGG16 model
VGG16 = models.vgg16(pretrained=True)
# set model to evaluation mode
VGG16.eval()
# do not track gradients for the model parameters
for param in VGG16.parameters():
param.requires_grad = False
# check if CUDA is available
use_cuda = torch.cuda.is_available()
# move model to GPU if CUDA is available
if use_cuda:
VGG16 = VGG16.cuda()
Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.
In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.
Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.
def VGG16_predict(img_path):
'''
Use pre-trained VGG-16 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to VGG-16 model's prediction
'''
## DONE: Complete the function.
## Load and pre-process an image from the given img_path
compose = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image = Image.open(img_path)
image = compose(image)
image = image[None,:]
if use_cuda:
image = image.cuda()
## Return the *index* of the predicted class for that image
prediction = VGG16(image)
# predicted class index
_, top_class = prediction.topk(1)
return top_class.item()
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).
Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
## DONE: Complete the function.
prediction = VGG16_predict(img_path)
# true/false
return prediction >= 151 and prediction <= 268
Question 2: Use the code cell below to test the performance of your dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer:
Dogs detected in human images 0.0%
Dogs detected in dog images 100.0%
### DONE: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
detections_in_human_files = np.mean([dog_detector(img) for img in human_files_short]) * 100
print(f'Dogs detected in human images\t{detections_in_human_files:.2f}%')
detections_in_dog_files = np.mean([dog_detector(img) for img in dog_files_short]) * 100
print(f'Dogs detected in dog images\t{detections_in_dog_files:.2f}%')
We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
### (Optional)
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
![]() |
![]() |
![]() |
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!
### DONE: Write data loaders for training, validation, and test sets
## Specify appropriate transforms, and batch_sizes
# avoid PIL to raise exception if find a truncated image
ImageFile.LOAD_TRUNCATED_IMAGES = True
# folder where the images are
data_dir = 'dogImages/'
# how many subprocesses to use for data loading
num_workers = 0 # data will be loaded in the main thread
# arrays to normalization
normalize_mean = np.array([0.485, 0.456, 0.406])
normalize_std = np.array([0.229, 0.224, 0.225])
## Specify transforms
data_transforms = {}
# transforms to train data set
data_transforms['train'] = transforms.Compose([
transforms.Resize(480),
transforms.RandomRotation(30),
transforms.RandomResizedCrop(224, scale=(224./480, 224./256), ratio=(1.,1.)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
transforms.Normalize(
normalize_mean,
normalize_std)
])
# transforms to valid data set
data_transforms['valid_test'] = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
normalize_mean,
normalize_std)
])
## Load the datasets with ImageFolder
image_datasets = {}
image_datasets['train_data'] = datasets.ImageFolder(data_dir + '/train', transform=data_transforms['train'])
image_datasets['valid_data'] = datasets.ImageFolder(data_dir + '/valid', transform=data_transforms['valid_test'])
image_datasets['test_data'] = datasets.ImageFolder(data_dir + '/test', transform=data_transforms['valid_test'])
## Using the image datasets and the transforms, define the dataloaders
dataloaders = {}
dataloaders['train_data'] = torch.utils.data.DataLoader(image_datasets['train_data'], batch_size=96, shuffle=True, num_workers=num_workers)
dataloaders['valid_data'] = torch.utils.data.DataLoader(image_datasets['valid_data'], batch_size=167, shuffle=False, num_workers=num_workers)
dataloaders['test_data'] = torch.utils.data.DataLoader(image_datasets['test_data'], batch_size=64, shuffle=False, num_workers=num_workers)
print(f"Train data: {len(dataloaders['train_data'].dataset)} images / {len(dataloaders['train_data'])} batches")
print(f"Valid data: {len(dataloaders['valid_data'].dataset)} images / {len(dataloaders['valid_data'])} batches")
print(f"Test data: {len(dataloaders['test_data'].dataset) } images / {len(dataloaders['test_data']) } batches")
Question 3: Describe your chosen procedure for preprocessing the data.
Answer:
Image size
I chose to work with an input image of 224x224 pixels which allows me to perform five downsizings (stride = 2), resulting in 7x7 tensors at the end of the convolutional layers. Also, that is not a too large image, which allows a faster training. Likewise, that is not a too small image, what still keep the relevant information.
Resizing the image
I perform the following steps to obtain the 224x224 pixels input image:
For the training data set:
For the validation and testing data set:
Data augmentation
I build my data augmentation method based on that I have found in the ResNet paper. Beyond that, I also added rotations. I use data augmentation only for the training data set.
Create a CNN to classify dog breed. Use the template in the code cell below.
# define the CNN architecture
class Net(nn.Module):
### DONE: choose an architecture, and complete the class
def __init__(self):
super(Net, self).__init__()
## Define layers of a CNN
## Convolutional layers
# in: 224x224 out: 112x112
self.conv1 = nn.Conv2d( 3, 64, 7, padding=3, stride=2)
self.conv1_bn = nn.BatchNorm2d( 64)
# in: 112x112 out: 56x56
self.conv2_1 = nn.Conv2d( 64, 64, 3, padding=1)
self.conv2_1_bn = nn.BatchNorm2d( 64)
self.conv2_2 = nn.Conv2d( 64, 64, 3, padding=1)
self.conv2_2_bn = nn.BatchNorm2d( 64)
# in: 56x56 out: 28x28
self.conv3_in = nn.Conv2d( 64, 128, 1, padding=1)
self.conv3_1 = nn.Conv2d(128, 128, 3, padding=1)
self.conv3_1_bn = nn.BatchNorm2d(128)
self.conv3_2 = nn.Conv2d(128, 128, 3, padding=1)
self.conv3_2_bn = nn.BatchNorm2d(128)
# in: 28x28 out: 14x14
self.conv4_in = nn.Conv2d(128, 256, 1, padding=1)
self.conv4_1 = nn.Conv2d(256, 256, 3, padding=1)
self.conv4_1_bn = nn.BatchNorm2d(256)
self.conv4_2 = nn.Conv2d(256, 256, 3, padding=1)
self.conv4_2_bn = nn.BatchNorm2d(256)
# in: 14x14 out: 7x7
self.conv5_in = nn.Conv2d(256, 512, 1, padding=1)
self.conv5_1 = nn.Conv2d(512, 512, 3, padding=1)
self.conv5_1_bn = nn.BatchNorm2d(512)
self.conv5_2 = nn.Conv2d(512, 512, 3, padding=1)
self.conv5_2_bn = nn.BatchNorm2d(512)
# Downsizing
self.maxpool = nn.MaxPool2d( 3, padding=1, stride=2)
# in: 7x7 out: 1x1
self.avgpool = nn.AvgPool2d(7)
# Activation
self.activation = nn.ReLU()
# Fully connected layers
self.fc = nn.Linear(512,133)
def forward(self, x):
## Define forward behavior
## Stack 1
x = self.conv1(x)
x = self.conv1_bn(x)
x = self.activation(x)
## Stack 2
shortcut = x
x = self.conv2_1(x)
x = self.conv2_1_bn(x)
x = self.activation(x)
x = self.conv2_2(x)
x = self.conv2_2_bn(x)
x = self.activation(x)
x += shortcut
x = self.maxpool(x)
## Stack 3
x = self.conv3_in(x)
x = self.activation(x)
shortcut = x
x = self.conv3_1(x)
x = self.conv3_1_bn(x)
x = self.activation(x)
x = self.conv3_2(x)
x = self.conv3_2_bn(x)
x = self.activation(x)
x += shortcut
x = self.maxpool(x)
## Stack 4
x = self.conv4_in(x)
x = self.activation(x)
shortcut = x
x = self.conv4_1(x)
x = self.conv4_1_bn(x)
x = self.activation(x)
x = self.conv4_2(x)
x = self.conv4_2_bn(x)
x = self.activation(x)
x += shortcut
x = self.maxpool(x)
## Stack 5
x = self.conv5_in(x)
x = self.activation(x)
shortcut = x
x = self.conv5_1(x)
x = self.conv5_1_bn(x)
x = self.activation(x)
x = self.conv5_2(x)
x = self.conv5_2_bn(x)
x = self.activation(x)
x += shortcut
x = self.maxpool(x)
x = self.avgpool(x)
# Classifier
x = x.squeeze()
x = self.fc(x)
return x
#-#-# You so NOT have to modify the code below this line. #-#-#
# instantiate the CNN
model_scratch = Net()
# move tensors to GPU if CUDA is available
use_cuda = torch.cuda.is_available()
if use_cuda:
model_scratch.cuda()
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.
Answer:
I developed my final CNN architecture inspired by the ResNet paper.
At first, I chose to start with a plain VGG-like model, with 5 convolutional layers and 3x3 filters, increasing the depth within each layer: 8, 16, 32, 64 and 128 filters.
That model reached 18% accuracy (156 of 836 test images).
Then, I decided I should add more layers, still following the VGG proposal, intending to get better performance. I doubled the number of convolutional layers, keeping the 3x3 filters, and I increased the depth to 32, 64, 128, 256 and 512 filters.
That model became heavy, and the training phase had been taking a long time to converge.
With my VGG-like model, I was facing the problem: a shallower network had not been performing good enough, and a deeper network had been converging too slow.
Thus, I went back to my researches to build a better architecture.
In the ResNet paper, I've found a path to speed the network convergence while increasing the depth: the Deep Residual Learning. The paper describes how making use of shortcuts can allow the network to backpropagate the error to the earlier layers, avoiding the vanishing gradient problem.
So, after studying the ResNet paper, I started modeling my final CNN architecture, as described below.
I converted my 5 convolutional layers into 5 convolutional stacks.
The first convolutional stack (named 'Conv1') generates 64 filters, 7x7 wide each, with a stride of 2, which reduces the input size by half.
The second convolutional stack (named 'Conv2') keeps the number of filters in 64, but has two convolutional layers and reduces the input size by half by using a max pooling layer with a stride of 2.
Here, the deep residual learning concept is introduced by adding shortcut connections between the stack input and the stack output.
After applying the last activation function over the last convolutional layer, the stack output receives the shortcut. Thus, the output of each stack would be written as y = f(x) + x.
Shortcuts have expedited the training of my network, allowing a deeper network architecture.
The next 3 stacks (named Conv3, Conv4, Conv5) follow the same principle of Conv2, but each stack doubles the number of filters at the beginning, by using 1x1 filters.
The last convolutional stack (Conv5) produces 512 filters, 7x7 wide each one. The output is given by a 7x7 average pool, generating 1 value for each filter; that means 1 vector with 512 positions. The classifier takes that vector and generates the dog breed predictions.
After some tests with that architecture, I reasoned that I had mitigated the vanishing gradient problem by using shortcuts, but the exploding gradients problem had taken place.
To solve that, I introduced batch normalization after each convolutional layer. Then, my network could converge to a better result.
My final CNN architecture has reached 74% accuracy (623 of 836 test images) after 120 epochs, training for about 11:30 hours.
Despite achieving a great result for a study of case CNN, that architecture shows up it could have its results leveraged by increasing the stack depth (by adding more convolutional layers), or even by increasing the number of filters inside each stack. For deeper networks, ResNet paper proposes one more improvement: "bottleneck" blocks, which would be added to my architecture to leverage its performance.
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.
### DONE: select loss function
criterion_scratch = nn.CrossEntropyLoss()
### DONE: select optimizer
optimizer_scratch = optim.Adagrad(model_scratch.parameters(), lr=0.01, weight_decay=0.001)
scheduler_scratch = optim.lr_scheduler.ReduceLROnPlateau(
optimizer_scratch, mode='min', factor=0.1, patience=14, verbose=True,
threshold=0.01, threshold_mode='abs', cooldown=0, min_lr=0, eps=1e-08)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda,
save_path, lr_scheduler=None):
"""returns trained model"""
# initialize tracker for minimum validation loss
valid_loss_min = np.Inf
# define how much epochs to train before run the validation loop
validate_for_each = 1
validate_after = 0
train_loss_trace = []
valid_loss_trace = []
for epoch in range(1, n_epochs+1):
# initialize variables to monitor training and validation loss
train_loss = 0.0
valid_loss = 0.0
###################
# train the model #
###################
model.train()
for batch_idx, (data, target) in enumerate(dataloaders['train_data']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
## find the loss and update the model parameters accordingly
# clear optimizer
optimizer.zero_grad()
# pass train batch through model feed-forward
output = model(data)
# calculate the loss fr this train batch
loss = criterion(output, target)
# do the backpropagation
loss.backward()
# optimize weights
optimizer.step()
## record the average training loss
train_loss += (1 / (batch_idx + 1)) * (loss.item() - train_loss)
sys.stdout.write(f'\rEpoch: {epoch} '+
f'\tTraining Loss: {train_loss:.6f} '+
f'\tbatchs: {batch_idx+1}')
train_loss_trace.append(train_loss)
######################
# validate the model #
######################
if epoch > validate_after and epoch % validate_for_each == 0:
model.eval()
with torch.no_grad():
for batch_idx, (data, target) in enumerate(dataloaders['valid_data']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# get predictions for this validation batch
output = model(data)
## update the average validation loss
# calculate loss for this validation batch
loss = criterion(output, target)
# Track validation loss
valid_loss += (1 / (batch_idx + 1)) * (loss.item() - valid_loss)
sys.stdout.write(f'\rEpoch: {epoch} '+
f'\tTraining Loss: {train_loss:.6f} '+
f'\tValidation Loss: {valid_loss:.6f} '+
f'\tbatchs: {batch_idx+1}')
valid_loss_trace.append(valid_loss)
# print training/validation statistics
print(f'\rEpoch: {epoch} '+
f'\tTraining Loss: {train_loss:.6f} '+
f'\tValidation Loss: {valid_loss:.6f}')
if lr_scheduler:
lr_scheduler.step(valid_loss)
## DONE: save the model if validation loss has decreased
if valid_loss < valid_loss_min:
print(f'\t\t\tValid loss decreasing: '+
f'{valid_loss_min:.6f} --> {valid_loss:.6f} ... Saving model')
checkpoint = {'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'train_loss_trace': train_loss_trace,
'valid_loss_trace': valid_loss_trace,
'epochs': epoch}
torch.save(checkpoint, save_path)
valid_loss_min = valid_loss
else:
valid_loss_trace.append(0)
print(f'\rEpoch: {epoch} '+
f'\tTraining Loss: {train_loss:.6f}')
# return trained model
return model
# train the model
checkpoint_path = gdrive_dir+'model_scratch.pt'
model_scratch = train(125, dataloaders, model_scratch, optimizer_scratch,
criterion_scratch, use_cuda, checkpoint_path, scheduler_scratch)
# load the model that got the best validation accuracy
checkpoint_path = gdrive_dir+'model_scratch.pt'
checkpoint = torch.load(checkpoint_path)
model_scratch.load_state_dict(checkpoint['model_state_dict'])
optimizer_scratch.load_state_dict(checkpoint['optimizer_state_dict'])
print('Loading trained model ... Epochs: {}\tTraining Loss: {}\t Valid Loss: {}'.format(
checkpoint['epochs'], checkpoint['train_loss_trace'][-1],
checkpoint['valid_loss_trace'][-1] ))
# Plot the training and validation losses
def plot_training_results(checkpoint):
fig, ax = plt.subplots(figsize=(30,8))
ax.set_facecolor('w')
ax.grid(True, color='lightgray')
ax.plot(checkpoint['train_loss_trace'], label='Training Loss')
ax.plot(checkpoint['valid_loss_trace'], label='Validation Loss')
ax.set_xlabel('Epochs')
ax.set_ylabel('Loss')
ax.legend(frameon=True, facecolor='w')
plt.show()
plot_training_results(checkpoint)
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.
def test(loaders, model, criterion, use_cuda):
# monitor test loss and accuracy
test_loss = 0.
correct = 0.
total = 0.
class_accuracy = torch.zeros(133)
class_size = torch.zeros(133)
model.eval()
for batch_idx, (data, target) in enumerate(loaders['test_data']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update average test loss
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
# convert output probabilities to predicted class
pred = output.data.max(1, keepdim=True)[1]
for label, prediction in zip(target.data, pred.squeeze()):
label, prediction = label.item(), prediction.item()
class_accuracy[label] += 1 if label == prediction else 0
class_size[label] += 1
correct, total = int(sum(class_accuracy)), int(sum(class_size))
print('Test Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct / total, correct, total))
class_accuracy = class_accuracy/class_size
class_accuracy = class_accuracy.view(7,19)
fig, ax = plt.subplots(figsize=(30,8))
ax.set_axis_off()
ax.grid(False)
im = ax.imshow(class_accuracy, cmap='RdYlGn')
cbar = ax.figure.colorbar(im, ax=ax)
cbar.ax.set_ylabel('accuracy', rotation=-90, va="bottom")
for i in range(class_accuracy.shape[0]):
for j in range(class_accuracy.shape[1]):
text_color = 'w' if class_accuracy[i, j] > 0.6 else 'k'
ax.text(j, i,
f'class: {j+i*19}\n{class_accuracy[i, j]*100:.0f}%',
ha="center", va="center", color=text_color)
# call test function
test(dataloaders, model_scratch, criterion_scratch, use_cuda)
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).
If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.
## DONE: Specify data loaders
# I have decided to use the same data loaders from the previous step.
# Doing this way, I can compare results from my network from scratch
# with the results from transfer learning.
Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.
## DONE: Specify model architecture
model_transfer = models.resnet152(pretrained=True)
# do not track gradients for the model parameters
for param in model_transfer.parameters():
param.requires_grad = False
fc_in_features = model_transfer.fc.in_features
fc_out_classes = 133
model_transfer.fc = nn.Linear(fc_in_features, fc_out_classes, bias=True)
if use_cuda:
model_transfer = model_transfer.cuda()
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer:
Since I have built my CNN from scratch inspired by the ResNet paper, I think I should use a pre-trained ResNet to build my transfer learning model. Doing this, I could compare the results from my model from scratch with the results of my transfer learning model.
Based on what I have learned in Lesson 3, I decided to change the last layer only (the fully connected layer). The pre-trained model has its weights trained on the ImageNet, a data set containing over 10 million images. My training data set contains 6680 images. Therefore, I realized I had no samples enough to perform a fine-tuning in the weights of the pre-trained network. Also, since the ImageNet covers the dog identification, the pre-trained model has already all information needed to identify the higher level features and to classify them into the dog breeds.
Thus, I froze all the pre-trained weights because I will not be training them. I merely replaced the classifier layer by using a fully connected layer, which receives the convolutional network output and generates the dog breed predictions. Then, I trained the network to update the weights of the new classifier.
At first, I chose to use the ResNet-18, because, among the other ResNet models, it has the most similar architecture in comparison with my model from scratch. After 30 epochs, my transfer learning model with ResNet-18 reached 83% accuracy (700 of 836 test images).
Since the ResNet-18 has been training in a huge training data set, I previously expected that it would perform better than my model from scratch. Furthermore, its architecture has been tested and improved for a long time. Despite that, I am glad to see my model from scratch performing not so worse than a state of the art model.
To the end, I changed the pre-trained network to the ResNet-152. I did that because I would like to compare the previous results with the heaviest ResNet available among the TorchVision models. As expected, ResNet-152 performed better than ResNet-18, but, surprisingly, not extraordinarily better. After 30 epochs, my transfer learning model with ResNet-152 reached 89% accuracy (746 of 836 test images). That same model, after 100 epochs, reached a slightly better result, with the same 89% accuracy, but predicting accurately only 4 more images (750 of 836 test images).
Of course, many other features could have its parameters fine-tuned, such as the optimizer, the learning rate, the training data augmentation, and so on. Maybe, fine-tuning those parameters could unlock all the ResNet-152 potential.
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.
### DONE: select loss function
criterion_transfer = nn.CrossEntropyLoss()
### DONE: select optimizer
optimizer_transfer = optim.Adagrad(model_transfer.fc.parameters(), lr=0.01, weight_decay=0.001)
scheduler_transfer = optim.lr_scheduler.ReduceLROnPlateau(
optimizer_transfer, mode='min', factor=0.1, patience=9, verbose=True,
threshold=0.01, threshold_mode='abs', cooldown=0, min_lr=0, eps=1e-08)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.
# Define the checkpoint path
checkpoint_path = gdrive_dir+'model_transfer.pt'
# train the model
model_transfer = train(100, dataloaders, model_transfer, optimizer_transfer,
criterion_transfer, use_cuda, checkpoint_path, scheduler_transfer)
# load the model that got the best validation accuracy
checkpoint = torch.load(checkpoint_path)
model_transfer.load_state_dict(checkpoint['model_state_dict'])
optimizer_transfer.load_state_dict(checkpoint['optimizer_state_dict'])
print('Loading trained model ... Epochs: {}\tTraining Loss: {}\t Valid Loss: {}'.format(
checkpoint['epochs'], checkpoint['train_loss_trace'][-1],
checkpoint['valid_loss_trace'][-1] ))
plot_training_results(checkpoint)
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.
test(dataloaders, model_transfer, criterion_transfer, use_cuda)
Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.
# list of class names by index, i.e. a name can be accessed like class_names[0]
class_sample_folders = ['dogImages/test/'+item for item in dataloaders['train_data'].dataset.classes]
class_names = [item[4:].replace("_", " ") for item in dataloaders['train_data'].dataset.classes]
### DONE: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.
def predict_breed_transfer(img_path):
# load the image and return the predicted breed
img = Image.open(img_path)
img = data_transforms['valid_test'](img)
img = img[None,:]
if next(model_transfer.parameters()).is_cuda:
img = img.cuda()
prediction = model_transfer(img)
prediction = nn.Softmax(dim=1)(prediction)
top_prob, top_class = prediction.topk(5, dim=1)
top_prob, top_class = top_prob.squeeze(), top_class.squeeze()
breeds = [(class_names[c.item()], p.item(), c.item())
for p, c in zip(top_prob, top_class)]
return breeds
rows = 6
cols = 4
dog_samples_idx = torch.randint(low=0, high=len(dog_files), size=(rows*cols,))
paths = [dog_files[idx] for idx in dog_samples_idx]
labels = [path.split('/')[2][4:].replace("_", " ") for path in paths]
predictions = [predict_breed_transfer(path) for path in paths]
fig, axs = plt.subplots(nrows=rows*2, ncols=cols, constrained_layout=True, figsize=(15, 28))
axs = axs.flatten()
row_ctrl = -1
rows *= 2
for pos, (path, label, prediction) in enumerate(zip(paths, labels, predictions)):
if pos % cols == 0:
row_ctrl += 1
img = Image.open(path)
title = f'{label}'
title_color = 'green' if label == prediction[0][0] else 'red'
position = pos + row_ctrl*cols
ax1 = axs[position]
ax1.imshow(img)
ax1.set_title(title, color=title_color)
ax1.grid(False)
ax1.set_yticks([])
ax1.set_xticks([])
breed_label = []
breed_prob = []
for breed in prediction:
breed_label.append(breed[0])
breed_prob.append(breed[1])
ax2 = axs[position+cols]
ax2.barh(np.arange(5), breed_prob)
ax2.set_yticks(np.arange(5))
ax2.set_yticklabels(breed_label)
ax2.set_ylim(-1, 5)
ax2.invert_yaxis()
ax2.set_xlim(0, 1.1)
plt.show()
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!

### DONE: Write your algorithm.
### Feel free to use as many code cells as needed.
# Set the threshold to consider as being purebred
purebred_threshold = 0.90
def run_app(img_path):
## handle cases for a human face, dog, and neither
fig, axs = plt.subplots(nrows=1, ncols=2, constrained_layout=True,
figsize=(10, 4), linewidth=4.0, edgecolor='k')
axs = axs.flatten()
# show the input image
img_height = 224
img = Image.open(img_path)
w, h = img.size
img = img.resize((int(w/h*img_height), img_height))
axs[0].imshow(img)
axs[0].set_facecolor('w')
axs[0].set_axis_off()
axs[0].grid(False)
# describe the input image
title = None
title_color = 'blue'
if dog_detector(img_path):
title = 'So cute dog!'
breeds = predict_breed_transfer(img_path)
if breeds[0][1] >= purebred_threshold:
title += '\nI see you as a purebred!'
axs[1].set_title(breeds[0][0].upper(), color=title_color,
fontsize='xx-large', fontweight='bold')
purebred_img = Image.open('purebred.png')
axs[1].imshow(purebred_img)
axs[1].set_facecolor('w')
axs[1].set_axis_off()
axs[1].grid(False)
else:
axs[1].set_title('I see you as a crossbred!',
color=title_color, fontsize='xx-large')
breeds = list(zip(*breeds))
axs[1].barh(np.arange(5), breeds[1])
axs[1].set_yticks(np.arange(5))
axs[1].set_yticklabels(breeds[0])
axs[1].set_ylim(-0.5, 4.5)
axs[1].invert_yaxis()
axs[1].set_xlim(0, 1.05)
elif face_detector(img_path) > 0:
breeds = predict_breed_transfer(img_path)
title = 'Hey human! For me, you look like a'
axs[1].set_title(breeds[0][0].upper(),
color=title_color, fontsize='xx-large')
class_id = breeds[0][2]
folder = class_sample_folders[class_id]
files_list = os.listdir(folder)
img_idx = np.random.randint(len(files_list))
sample_image_path = folder+'/'+files_list[img_idx]
sample_image = Image.open(sample_image_path)
w, h = sample_image.size
sample_image = sample_image.resize((int(w/h*img_height), img_height))
axs[1].imshow(sample_image)
axs[1].set_axis_off()
axs[1].grid(False)
else:
title = 'Sorry, I could detect neither dogs or humans in this image.'
title_color = 'red'
no_dogs_img = Image.open('no_dogs_detected.png')
axs[1].imshow(no_dogs_img)
axs[1].set_facecolor('w')
axs[1].set_axis_off()
axs[1].grid(False)
axs[0].set_title(title, color=title_color, fontsize='xx-large')
plt.show()
# Predictions for dogs
dog_samples_idx = torch.randint(low=0, high=len(dog_files), size=(10,))
for idx in dog_samples_idx:
run_app(dog_files[idx])
print()
# Predictions for humans
human_samples_idx = torch.randint(low=0, high=len(human_files), size=(10,))
for idx in human_samples_idx:
run_app(human_files[idx])
print()
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: (Three possible points for improvement)
I had a good time while developing this project.
I have worked hard to develop my CNN from scratch, but it worthed each minute that I spent on it! It is very gratifying to see my model performing so well.
However, I reached a better result by using transfer learning, as expected.
Seeing the resembling dog breed for a human image in comparison with a real dog image, made my day!
Despite that, my final result did not perform as well as I expected while predicting my photos.
It was able to detect correctly photos where had or not dogs, but it was not able to predict the dog breed of dogs in my photos. That upset me a little. I don't know what went wrong. If the color saturation in the photos, the position of the dogs, or something else. I should run more tests with more images to identify potential causes to the mismatching of my final model.
Possible points of improvement of my algorithm:
## DONE: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
run_app('johnny.jpg')
print()
run_app('blue.jpg')
print()
run_app('silvio.jpg')
print()
run_app('luciana.jpg')
print()
run_app('cidinha.jpg')
print()
run_app('silviao.jpg')
print()
run_app('graziela.jpg')
print()
run_app('marcelo.jpg')
print()
run_app('vicky.jpg')
print()
run_app('taco.jpg')
print()
run_app('sealion.jpg')
print()
run_app('madonna_1.jpg')
print()
run_app('madonna_2.jpg')
print()
run_app('Fred_the_Bassador.jpg')
print()
run_app('Pomsky_Dog_Breed_-_Pomeranian_Husky_Mix.jpg')
print()
run_app('Huskamute_facial_expression.jpg')
print()
run_app('cat_adriana.jpg')
print()